package website.seamonster.ethegg.service.background;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import website.seamonster.ethegg.conf.SystemConfig;
import website.seamonster.ethegg.dataobject.Chicken;
import website.seamonster.ethegg.dataobject.Egg;
import website.seamonster.ethegg.enums.EggStatusEnum;
import website.seamonster.ethegg.repository.ChickenRepository;
import website.seamonster.ethegg.repository.EggRepository;
import website.seamonster.ethegg.utils.BatchNumUtils;

import javax.transaction.Transactional;
import java.math.BigDecimal;

/**
 * Created by 罗海量
 * 2018-07-18 01:13
 */
@lombok.extern.slf4j.Slf4j
@Service
public class BornEggService {
    @Autowired
    private EggRepository eggRepository;

    @Autowired
    private ChickenRepository chickenRepository;

    /**
     * （特定鸡）生一只蛋【暂时只会出现在一次完成的交易后：买了一只鸡or卖出一只蛋】
     * @param chicken
     */
    @Transactional
    public void bornEgg(Chicken chicken){
        //判断鸡是否已死亡
        if (!chicken.isAlive()){
            return;
        } else if (chicken.getBornNum()>= SystemConfig.MAX_BORN_EGG_NUM){
            chicken.setAlive(false);
            chickenRepository.save(chicken);
            return;
        }

        //新增一只蛋
        this.generateEgg(chicken);

        //鸡的生蛋数+1
        int bornNum = chicken.getBornNum() + 1;
        //该鸡生完4只蛋后，该孵化圈关闭，鸡死亡
        if (bornNum >= SystemConfig.MAX_BORN_EGG_NUM){
            chicken.setAlive(false);
        }
        chicken.setBornNum(bornNum);
        chickenRepository.save(chicken);

        //蛋计数器+1 留给异步
    }

    private void generateEgg(Chicken chicken) {
        Egg egg = new Egg();
        egg.setUserId(chicken.getUserId());

        long maxSeq = eggRepository.getMaxSeq() + 1;
        int batchNum = BatchNumUtils.getBatchNumFromCount(maxSeq);
        BigDecimal price = SystemConfig.ALAPHA_PRICE.pow(batchNum);
        egg.setBatchNum(batchNum);
        egg.setSeq(maxSeq);
        egg.setChickenId(chicken.getId());
        egg.setPrice(price);

        /*
        【注意】 下边部分估计是bug重灾区
        */
        //寻找"出售"状态中，次序最先的蛋
        Egg lastSellingEgg = eggRepository.findFirstByEggStatusOrderBySeqDesc(EggStatusEnum.SALE.getCode());
        if (lastSellingEgg == null) {
            //已经没有出售中的蛋了，新出生的蛋的状态设为"出售中"
            egg.setEggStatus(EggStatusEnum.SALE.getCode());
            //所有与新生蛋同一批次的蛋也设置为"出售中"
            eggRepository.updateEggStatusByBatch(EggStatusEnum.SALE.getCode(), EggStatusEnum.PRE.getCode(), batchNum);
        } else {
            int sellingBatchNum = lastSellingEgg.getBatchNum();
            if (batchNum > sellingBatchNum){
                //新生蛋的批次大于出售中的蛋的批次，新出生的蛋的状态设为"待售中"
                egg.setEggStatus(EggStatusEnum.PRE.getCode());
            } else {
                //与出售中的蛋属于同一批次，新出生的蛋的状态设为"出售中"
                egg.setEggStatus(EggStatusEnum.SALE.getCode());
                //所有与新生蛋同一批次的蛋也设置为"出售中"
                eggRepository.updateEggStatusByBatch(EggStatusEnum.SALE.getCode(), EggStatusEnum.PRE.getCode(), batchNum);
            }
        }

        eggRepository.save(egg);
    }

    //产出初始的100只蛋, 批次为0，次序为0，价格为1
    public void bornEggSystem(){
        for (int i=0; i<100; i++){
            Egg egg = new Egg();
            egg.setBatchNum(0);
            egg.setSeq(0);
            egg.setPrice(new BigDecimal(1));
            egg.setEggStatus(EggStatusEnum.SALE.getCode());
            eggRepository.save(egg);
        }
    }

    /**
     * 蛋孵化成鸡
     * （然后鸡马上会下一只蛋）
     * @param eggId
     * @param userId
     */
    @Transactional
    public void eggToChicken(Long eggId, String userId){
        log.debug("Egg brood to chicken! egg id:{}, userId:{}", eggId, userId);
        //修改蛋的状态为"已孵化"
        Egg egg = eggRepository.findOne(eggId);
        egg.setEggStatus(EggStatusEnum.FINISHED.getCode());
        eggRepository.save(egg);

        //新增一只鸡
        Chicken chicken = new Chicken();
        chicken.setAlive(true);
        chicken.setBornNum(0);
        chicken.setUserId(userId);
        Chicken chickenUpdate = chickenRepository.save(chicken);

        //下一蛋
        this.bornEgg(chickenUpdate);

    }



}
